from database_util import get_daily_report_info
from os import system
from daily_report_auto_db import start
from time import sleep
from datetime import datetime
from random import randint
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formataddr
from smtplib import SMTP_SSL
from time import strftime, localtime

my_sender = '发件人邮箱账号'  # 发件人邮箱账号
my_pass = '发件人邮箱密码(当时申请smtp给的口令)'  # 发件人邮箱密码(当时申请smtp给的口令)

def mail_send_with_user(content, subject, sender, getter):
    global my_pass

    try:
        msg_text = MIMEText(str(content), "html", "utf-8")
        msg = MIMEMultipart('related')
        msg.attach(msg_text)
        msg['From'] = formataddr([sender, sender])  # 括号里的对应发件人邮箱昵称、发件人邮箱账号
        msg['Subject'] = subject

        server = SMTP_SSL("smtp.qq.com", 465)
        server.login(my_sender, my_pass)  # 括号中对应的是发件人邮箱账号、邮箱密码

        msg['To'] = formataddr([getter, getter])  # 括号里的对应收件人邮箱昵称、收件人邮箱账号
        server.sendmail(my_sender, getter, msg.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
        server.quit()
        print(">>> 《%s》 发送成功" % subject, strftime("%Y-%m-%d %H:%M:%S", localtime()))
        return True
    except Exception as e:
        print(e)
        return False


if __name__ == '__main__':
    print('**************UESTC自动每日健康填报程序**************')
    checktime = datetime.now().strftime("%Y-%m-%d")
    try:
        while True:
            users = get_daily_report_info()
            if users == []:
                today = datetime.now().strftime("%Y-%m-%d")
                print(">>> 今日全部打卡完毕！%s" % today)
                if checktime != today:
                    mail_send_with_user('今日全部打卡完毕！', 'UESTC 每日健康填报结果', my_sender, 'lzc980202@163.com')
                    checktime = today
            else:
                for user in users:
                    print(">>> 填报人：%s" % user[1])
                    start(user_id=user[0], stu_num=user[2], password=user[3], email=user[4])
                    sleep(randint(30, 40))
            print("check information... %s >>>" % datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
            sleep(7200)
    except KeyboardInterrupt:
        print("* 手动终止运行")
    except Exception as e:
        print(e)
        system("python main.py")
    finally:
        input('> 按任意键退出')
